const fs = require('fs')
const path = require('path')
const glob = require("glob")
const chokidar = require('chokidar')
const Koa = require('koa')
const serve = require('koa-static-server')
const websockify = require('koa-websocket')

const less = require('less')

const app = websockify(new Koa())

app.use(serve({ rootDir: 'dist', rootPath: '/' }))

app.ws.use(function (ctx, next) {
  ctx.websocket.on('message', function (message) {
    // do something
  })
  return next(ctx)
})

const renderLess = async (lessFilePath) => {
  let lessFileContent = fs.readFileSync(lessFilePath, { encoding: 'utf-8' })
  let lessRenderRes = await less.render(lessFileContent)

  let targetPath = path.join(__dirname, '../dist', lessFilePath.substring('src/'.length, lessFilePath.length))
  let targetDir = path.dirname(targetPath)
  let targetName = path.basename(targetPath, '.less') + '.css'
  if (!fs.existsSync(targetDir)) {
    fs.mkdirSync(targetDir, { recursive: true })
  }
  fs.writeFileSync(path.join(targetDir, targetName), lessRenderRes.css, { encoding: 'utf-8' })
}

const watchAndRenderLess = () => {
  glob("src/**/*.less", {}, function (er, files) {
    files.forEach(renderLess)
  })
  const watcher = chokidar.watch("src/**/*.less")
  watcher.on('all', (e, path, stats) => {
    console.log(e, path, stats != null)
    if (e == 'add' || e == 'change' || e == 'addDir') {
      renderLess(path)
    }
  })
}
//TODO 还未处理dist多余文件问题
watchAndRenderLess()

app.listen(3000)
console.log('http://localhost:3000')